<template>
  <div id="wraper">
    <article id="map1"></article>
    <span id="layerToggle" class="widget">
      <input type="checkbox" id="streetsLayer" checked /> Transportation
    </span>
  </div>
</template>

<script>
import { loadModules } from "esri-loader";

export default {
  name: "app",
  data() {
    return {
      basemap: ["topo-vector", "streets"],
      coordinateLngLats: [],
    };
  },
  mounted() {
    this.coordinateLngLats.push({coordinateLngLat: '1126.197174,1.543534',zhy: 'abc'})
    this._createMapView();
    // this.createMap();
  },
  methods: {
    //创建地图
    _createMapView() {
      const _self = this; //定义一个_self防止后续操作中this丢失
      const option = {
        //定义一个包含有JS API中js开发包和css样式文件的对象
        url: "http://localhost/4.14/init.js",
        css: "http://localhost/4.14/esri/themes/light/main.css",
      };
      //通过loadModules来做衔接 (注意他们引入的顺序)
      loadModules(
        [
          "esri/rest/locator",
          "esri/Map", // 地图
          "esri/Graphic",
          // "esri/views/SceneView", // 3d地图
          "esri/views/MapView", // 2d地图
          "esri/layers/TileLayer", // TileLayer 是创建图层的
          "esri/widgets/BasemapToggle", // 创建小部件
          "esri/layers/GraphicsLayer"
        ],
        option
      )
        .then(([locator, Map, MapView, TileLayer, Graphic, BasemapToggle, GraphicsLayer]) => {
          // TileLayer 创建层 目前可以通过页面中的checkbox控制显示隐藏
          const transportationLayer = new TileLayer({
            url: "https://server.arcgisonline.com/arcgis/rest/services/Reference/World_Transportation/MapServer",
            id: "streets",
            opacity: 0.7,
          });
          const housingLayer = new TileLayer({
            url: "https://tiles.arcgis.com/tiles/nGt4QxSblgDfeJn9/arcgis/rest/services/New_York_Housing_Density/MapServer",
            id: "ny-housing",
          });
          /**
           * 业务代码在此处编写
           */
          const map = new Map({
            //实例化地图
            basemap: this.basemap[0],
            ground: "topo-vector",
            layers: [housingLayer],
          });
          map.layers.add(transportationLayer); // layers第二种添加的方式

          const view = new MapView({
            //实例化地图视图
            container: "map1",
            map: map,
            zoom: 4,
            center: [15, 65],
          });

          // BasemapToggle 小部件, 现在创建了一个切换底图的小部件
          const toggle = new BasemapToggle({
            view: view,
            nextBasemap: "hybrid",
          });
          // 添加
          view.ui.add(toggle, "top-right");

          const locatorUrl =
            "https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer";
          const params = {
            location: event.mapPoint,
          };

              view.popup.autoOpenEnabled = false;
              view.on("click", (event) => {
                const lat = Math.round(event.mapPoint.latitude * 1000) / 1000;
                const lon = Math.round(event.mapPoint.longitude * 1000) / 1000;
    
                view.popup.open({
                  title: "Reverse geocode: [" + lon + ", " + lat + "]",
                  location: event.mapPoint, 
                });
              });
          locator
            .locationToAddress(locatorUrl, params)
            .then((response) => {
              view.popup.content = response.address;
            })
            .catch(() => {
              view.popup.content = "No address was found for this location";
            });

          //添加图片修饰点
          var lineSymbol = {
            type: "picture-marker",
            url: this.markpic,
            width: "32px",
            height: "32px",
          };
          var redLineSymbol = {
            type: "picture-marker",
            url: this.redMarkpic,
            width: "32px",
            height: "32px",
          };
          let zhy = [];
          this.coordinateLngLats.forEach((a) => {
            let coordinateLngLat = a.coordinateLngLat;
            var point = {
              //创建点，并确定点的经度和纬度
              type: "point",
              x: coordinateLngLat.split(",")[0],
              y: coordinateLngLat.split(",")[1],
            };
            var template = {
              content: "<span>这里可以写弹出框的内容:" + a.zhy + "</span>",
            };
            // 这里模拟逻辑判断切换展示颜色
            var result = true;
            var polylineGraphic = new Graphic({
              //绘制点
              geometry: point,
              symbol: result ? redLineSymbol : lineSymbol,
              attributes: {},
              popupTemplate: template,
            });
            zhy.push(polylineGraphic);
          });
          //将绘制的点加入地图图层
          view.graphics.addMany(zhy);

          // view.ui.components = []; //清除掉地图左上角默认的缩放图标
          const streetsLayerToggle = document.getElementById("streetsLayer");

          // Listen to the change event for the checkbox
          streetsLayerToggle.addEventListener("change", () => {
            transportationLayer.visible = streetsLayerToggle.checked; // 控制Layer创建层的显示隐藏
          });
        })
        .catch((err) => {
          _self.$message("地图创建失败，" + err);
        });
    },
    createMap() {
      loadModules([
        "esri/Map",
        "esri/views/MapView",
        "esri/layers/TileLayer",
        "esri/Graphic",
        "esri/widgets/Fullscreen",
        "esri/widgets/Zoom",
        "dojo/domReady!",
      ]).then(
        ([Map, MapView, TileLayer, Graphic, Fullscreen, Zoom]) => {
          var transportationLayer = new TileLayer({
            url: "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetGray/MapServer",
            id: "streets",
          });
          // 地图
          const map = new Map({
            // 底图的图层
            layers: [transportationLayer],
          });
          //  生成地图对象 mapview
          const mapview = new MapView({
            map: map,
            container: "map1", // dom元素
            zoom: 12, // 缩放
            center: [116.19432, 29.911222], // 位置
          });
          //清空左上角组件
          mapview.ui.empty("top-left");
          mapview.ui.add(
            //在右上角添加全屏组件
            new Fullscreen({
              view: mapview,
            }),
            "top-right"
          );
          //在右上角添加缩放组件
          mapview.ui.add(new Zoom({ view: mapview }), "top-right");
          //添加图片修饰点
          var lineSymbol = {
            type: "picture-marker",
            url: this.markpic,
            width: "32px",
            height: "32px",
          };
          var redLineSymbol = {
            type: "picture-marker",
            url: this.redMarkpic,
            width: "32px",
            height: "32px",
          };
          let zhy = [];
          this.coordinateLngLats.forEach((a) => {
            let coordinateLngLat = a.coordinateLngLat;
            var point = {
              //创建点，并确定点的经度和纬度
              type: "point",
              x: coordinateLngLat.split(",")[0],
              y: coordinateLngLat.split(",")[1],
            };
            var template = {
              content: "<span>这里可以写弹出框的内容:" + a.zhy + "</span>",
            };
            // 这里模拟逻辑判断切换展示颜色
            var result = true;
            var polylineGraphic = new Graphic({
              //绘制点
              geometry: point,
              symbol: result ? redLineSymbol : lineSymbol,
              attributes: {},
              popupTemplate: template,
            });
            zhy.push(polylineGraphic);
          });
          //将绘制的点加入地图图层
          mapview.graphics.addMany(zhy);
        },
        (reason) => {
          console.log(reason);
        }
      );
    },
  },
};
</script>

<style>
html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}
.main {
  position: absolute;
  top: 70px;
  bottom: 0;
  width: 100%;
}
#map1 {
  width: 100%;
  height: 100vh;
}
.widget {
  width: 80px;
  height: 30px;
  position: absolute;
  top: 20px;
  right: 100px;
  z-index: 99;
}
</style>
